<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>RSA 加密登录</title>
</head>

<body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.2/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.3.1/jsencrypt.min.js"></script>
<script>
  const storage = {
    set(key, value) {
      localStorage.setItem(key, JSON.stringify(value));
    },
    get(key) {
      return localStorage.getItem(key);
    },
    remove(key) {
      localStorage.removeItem(key);
    }
  }


  let publicKey = '';

  async function getPublicKey() {
    let key = storage.get('ua_publicKay')
    if (!key || key === 'undefined') {
      let result = await axios.get('http://127.0.0.1:3005/keys', {})
      console.log("-> result", result);
      key = result.data.data.pubKey
      var key1 = key
      console.log("-> key1", key);
      key = key.replace(/\. +/g, '')
      key = key.replace(/[\r\n]/g, '')
      var key2 = key
      console.log("-> key2", key);
      console.log("-> key1==key2", key == key2);
      publicKey = key
      storage.set('ua_publicKay', key)
    }
    return key
  }

  function getKey() {
    return storage.get('ua_publicKay')
  }

  // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么

    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });


  /*     getPublicKey().then(key => {
        axios.post('http://127.0.0.1:3005/admin/login', {
          username: "admin123",
          password: encrypt(key, 'Wdd123456')
        }).then(data => {
          console.log(data)
        })
      })*/
  getPublicKey().then(key => {
    console.log(key)
    // axios.post('http://127.0.0.1:3005/admin/register', {
    //   username: "admin123",
    //   password: encrypt(key, 'Hello.123'),
    //   email: "39333@qq.com"
    // }).then(data => {
    //   console.log(data)
    // })
  })

  function encrypt(publicKey, value) {
    let encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    return encrypt.encrypt(value)
  }


</script>
</body>

</html>
